<template>
  <div class="stock-in-report">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 100px">
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.warehouseName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="入库类型">
            <el-select v-model="searchForm.stockInType" placeholder="请选择入库类型" clearable style="width: 100px">
              <el-option label="采购入库" value="PURCHASE" />
              <el-option label="退货入库" value="RETURN" />
              <el-option label="其他入库" value="OTHER" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计卡片 -->
      <div class="stat-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">入库单数</div>
              </template>
              <div class="stat-value">{{ statistics.orderCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">入库商品数</div>
              </template>
              <div class="stat-value">{{ statistics.productCount }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">入库总数量</div>
              </template>
              <div class="stat-value">{{ statistics.totalQuantity }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card">
              <template #header>
                <div class="stat-header">入库总金额</div>
              </template>
              <div class="stat-value">¥{{ formatAmount(statistics.totalAmount) }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="chart-area">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-title">入库类型分布</div>
              </template>
              <div class="chart-container" ref="typeChartContainer"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-title">入库金额趋势</div>
              </template>
              <div class="chart-container" ref="trendChartContainer"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 明细表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column prop="stockInDate" label="入库日期" width="100" />
        <el-table-column prop="stockInCode" label="入库单号" width="160" />
        <el-table-column label="入库类型" width="100">
          <template #default="scope">
            <el-tag :type="getStockInTypeTag(scope.row.stockInType)">
              {{ getStockInTypeLabel(scope.row.stockInType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="仓库" width="120">
          <template #default="scope">
            {{ getWarehouseName(scope.row.warehouseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="200" />
        <el-table-column prop="specifications" label="规格" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" align="right" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column label="单价" width="120" align="right">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120" align="right">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="经办人" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, toRaw } from 'vue'
import * as echarts from 'echarts'
import { stockInApi, warehouseApi, productApi } from '../../api'
// 从localStorage获取仓库列表
const getWarehouseList = async () => {
  try {
    const { data } = await warehouseApi.getList()
    warehouseList.value = data.records.filter(item => item.status === 1) || []
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}

// 仓库列表
const warehouseList = ref([])

// 获取仓库名称
const getWarehouseName = (warehouseId) => {
  const warehouse = warehouseList.value.find(item => item.id === warehouseId)
  return warehouse ? warehouse.warehouseName : ''
}

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  warehouseId: '',
  stockInType: ''
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const statistics = reactive({
  orderCount: 0,
  productCount: 0,
  totalQuantity: 0,
  totalAmount: 0
})

// 图表容器引用
const typeChartContainer = ref(null)
const trendChartContainer = ref(null)

// 图表实例
let typeChart = null
let trendChart = null

// 获取数据并统计
const getReportData = async () => {
  loading.value = true
  try {
    // 构建查询参数 - 不使用分页参数获取所有入库单
    const params = {
      warehouseId: searchForm.warehouseId || undefined,
      stockInType: searchForm.stockInType || undefined,
      startDate: searchForm.dateRange?.[0] || undefined,
      endDate: searchForm.dateRange?.[1] || undefined
    }

    // 获取入库单列表
    const { data } = await stockInApi.getListAll(params)
    const stockInList = data || []
    
    // 获取每条记录的明细数据
    const allDetailList = []
    for (const stockIn of stockInList) {
      if (stockIn.items) {

        // 将商品信息添加到明细中
        stockIn.items.forEach(item => {
          allDetailList.push({
            ...item,
            stockInCode: stockIn.stockInCode,
            stockInDate: stockIn.stockInDate.split(' ')[0],
            stockInType: stockIn.stockInType,
            warehouseId: stockIn.warehouseId,
            operator: stockIn.operator,
            productCode: item?.productCode,
            productName: item?.productName,
            specifications: item?.specifications,
            unit: item?.unit
          })
        })
      }
    }

    // 更新统计数据 - 使用所有明细数据进行统计
    statistics.orderCount = stockInList.length
    statistics.productCount = new Set(allDetailList.map(item => item.productId)).size
    statistics.totalQuantity = allDetailList.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
    statistics.totalAmount = allDetailList.reduce((sum, item) => sum + Number(item.amount || 0), 0)

    // 手动处理分页
    total.value = allDetailList.length
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    tableData.value = allDetailList.slice(startIndex, endIndex)

    // 更新图表 - 使用所有数据
    updateCharts(stockInList, allDetailList)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = (stockInList, detailList) => {
  if (!typeChart || !trendChart) return

  // 入库类型分布图
  const typeData = [
    { name: '采购入库', value: 0 },
    { name: '退货入库', value: 0 },
    { name: '其他入库', value: 0 }
  ]
  
  // 使用明细数据计算金额
  detailList.forEach(item => {
    switch(item.stockInType) {
      case 'PURCHASE':
        typeData[0].value += item.amount
        break
      case 'RETURN':
        typeData[1].value += item.amount
        break
      case 'OTHER':
        typeData[2].value += item.amount
        break
    }
  })

  typeChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: typeData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 入库金额趋势图
  const dateMap = new Map()
  detailList.forEach(item => {
    const date = item.stockInDate
    dateMap.set(date, (dateMap.get(date) || 0) + item.amount)
  })

  const dates = Array.from(dateMap.keys()).sort()
  const amounts = dates.map(date => dateMap.get(date))

  trendChart.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>入库金额: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        data: amounts,
        type: 'line',
        smooth: true,
        areaStyle: {}
      }
    ]
  })
}

// 初始化图表
const initCharts = () => {
  // 确保DOM已经渲染
  if (typeChartContainer.value && trendChartContainer.value) {
    // 销毁旧的实例
    typeChart?.dispose()
    trendChart?.dispose()
    
    // 创建新的实例
    typeChart = echarts.init(typeChartContainer.value)
    trendChart = echarts.init(trendChartContainer.value)
    
    // 初始化时立即获取数据
    getReportData()
  }
}

// 监听窗口大小变化
const handleResize = () => {
  typeChart?.resize()
  trendChart?.resize()
}

// 组件挂载时
onMounted(async () => {
  await getWarehouseList()  // 先获取仓库列表
  initCharts()  // 然后初始化图表
  window.addEventListener('resize', handleResize)
})

// 组件卸载时
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  typeChart?.dispose()
  trendChart?.dispose()
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getReportData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.dateRange = []
  searchForm.warehouseId = ''
  searchForm.stockInType = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getReportData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getReportData()
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null || isNaN(amount)) {
    return '0.00'
  }
  return Number(amount).toFixed(2)
}

// 入库类型
const getStockInTypeLabel = (type) => {
  const types = {
    'PURCHASE': '采购入库',
    'RETURN': '退货入库',
    'OTHER': '其他入库'
  }
  return types[type] || type
}

const getStockInTypeTag = (type) => {
  const types = {
    'PURCHASE': '',
    'RETURN': 'warning',
    'OTHER': 'info'
  }
  return types[type] || ''
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      warehouseId: searchForm.warehouseId || undefined,
      stockInType: searchForm.stockInType || undefined,
      beginTime: searchForm.dateRange?.[0] || undefined,
      endTime: searchForm.dateRange?.[1] || undefined
    }
    
    await stockInApi.exportReport(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}
</script>

<style scoped>
.stock-in-report {
  height: 100%;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  min-width: 1200px;
}

/* 确保卡片内容可以滚动 */
.el-card {
  height: 100%;
  overflow-y: auto;
}

.search-area {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-header {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-top: 10px;
}

.chart-area {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>